/**
 * 抖音/头条/西瓜 广告
 * 抖音不支持 banner 和 插屏
 */
let BannerAdUtils = {

    _gBanner:null,
    systemInfo:null,

    _requestBanner(){

        if(!dyAds.isInited()){
            throw new Error(`请先 调用 dyAds.init(bannerAdId,intersisterAdId,videoAdId) 进行初始化. `);
        }

        if(!this.systemInfo){
            this.systemInfo = tt.getSystemInfoSync();
            console.log('this.systemInfo:',this.systemInfo);
        }

        let windowWidth = this.systemInfo.windowWidth;
        let windowHeight = this.systemInfo.windowHeight;

        let targetBannerAdWidth = 208;
        let left = (windowWidth - targetBannerAdWidth ) / 2;
        console.log('left:',left);

        // 创建一个居于屏幕底部正中的广告
        let bannerAd = tt.createBannerAd({
            adUnitId: dyAds.getBannerAdId(),
            style: {
                width: targetBannerAdWidth,
                top: windowHeight - (targetBannerAdWidth / 16) * 9, // 根据系统约定尺寸计算出广告高度
                left: left,
            },
        });


        bannerAd.onResize((size) => {
            // good
            console.log(size.width, size.height);
            bannerAd.style.top = windowHeight - size.height;
            bannerAd.style.left = (windowWidth - size.width) / 2;

            // bad，会触发死循环
            // bannerAd.style.width++;
        });

        bannerAd.onLoad(()=>{
            console.log('Banner 加载成功...');
            bannerAd
                .show()
                .then(() => {
                    console.log("广告显示成功");
                })
                .catch((err) => {
                    console.log("广告组件出现问题", err);
                });
        });
        bannerAd.onError((err)=>{
            console.log('Banner 加载失败... err:',err);
        });
        this._gBanner = bannerAd;
    },

    _removeBanner(){
        if(this._gBanner){
            this._gBanner.destroy();
            this._gBanner = null;
            // this._hasBanner = false;
            console.log('_removeBanner success!');
        }
    },

    //---------------------------------------
    // apis
    showBannerAd(){
        if(!tt.createBannerAd){
            return;
        }

        if(this._gBanner){
            this._removeBanner();
            setTimeout(this._requestBanner.bind(this),50);
        }else{
            this._requestBanner();
        }
    },

    hideBanner(){
        this._removeBanner();
    }
};

let InterstitialAdUtils = {

    _gInterAd:null,
    systemInfo:null,

    _removeInterAd(){
        if(this._gInterAd){
            this._gInterAd.destroy();
            this._gInterAd = null;
            // this._hasInterAd = false;
            console.log('remove interAd success!');
        }
    },

    _requestInterAd(){
        if(!dyAds.isInited()){
            throw new Error(`请先 调用 dyAds.init(bannerAdId,intersisterAdId,videoAdId) 进行初始化. `);
        }
        const interstitialAd = tt.createInterstitialAd({
            adUnitId: dyAds.getIntersistAdId(),
        });
        interstitialAd
            .load()
            .then(() => {
                interstitialAd.show();
            })
            .catch((err) => {
                console.log(err);
            });

        interstitialAd.onClose(()=>{
           this._removeInterAd();
        });

        this._gInterAd = interstitialAd;
        // this._hasInterAd = true;
    },

    //-----------------------------
    // apis
    showInterstialAd(){

        if(!tt.createInterstitialAd){
            return;
        }

        if(!this.systemInfo){
            this.systemInfo = tt.getSystemInfoSync();
        }

        const isToutiaio = this.systemInfo.appName === "Toutiao";

        if(!isToutiaio){
            return;
        }

        if(this._gInterAd){
            this._removeInterAd();
            setTimeout(this._requestInterAd.bind(this),50);
        }else{
            this._requestInterAd();
        }
    }
};

let VideoAdUtils = {

    _cacheSuccess:false,
    _gVideoAd:null,
    _videoCallback:null,

    _createVideoAd(){

        if(!dyAds.isInited()){
            throw new Error(`请先 调用 dyAds.init(bannerAdId,intersisterAdId,videoAdId) 进行初始化. `);
        }

        let videoAd = tt.createRewardedVideoAd({
            adUnitId:dyAds.getVideoAdId(),
        });
        videoAd.onLoad(()=>{
            console.log('激励视频加载成功');
            this._cacheSuccess = true;
        });

        videoAd.onError(err=>{
           console.log('激励视频加载失败:',err);
           cc.director.resume(); // 可能是播放异常
            this._cacheSuccess = false;
        });

        videoAd.onClose((res)=>{

            cc.director.resume();

            let complete = false;
            if (res.isEnded) {
                // 给予奖励
                // TODO: 给与视频奖励
                complete = true;
            }

            if(this._videoCallback){
                // 视频播放完毕
                if(complete){
                    this._videoCallback(ShSdk.OP_PLAY_VIDEO);
                }else{
                    // 视频还没有播放完毕
                    window.ShSdk.videoUnFinishTip('完全观看才能获取奖励.');
                }
            }

            this.cacheVideoAd();
        });

        this._gVideoAd = videoAd;
    },

    //---------------------------------
    // apis
    // 游戏启动后
    cacheVideoAd(){
        if(!tt.createRewardedVideoAd){
            return;
        }

        if(this._gVideoAd){
            this._gVideoAd.load();
        }else{
            this._createVideoAd();
        }
    },

    showVideoAd(videoCb){

        this._videoCallback = videoCb;

        if(!this._gVideoAd){
            this.cacheVideoAd();
            return;
        }

        if(this._cacheSuccess){
            this._gVideoAd.show().then(()=>{
                // 暂停游戏引擎
                cc.director.pause();
            });
        }else{
            this.cacheVideoAd();
        }
    },

    videoCachedSuccess(){
        return this._cacheSuccess;
    }
};

let dyAds = {

    _bInited:false,
    _BannerAdId:null,
    _IntersisterAdId:null,
    _VideoAdId:null,

    BannerAdUtils:BannerAdUtils,
    InterstitialAdUtils:InterstitialAdUtils,
    VideoAdUtils:VideoAdUtils,

    init(bannerAdId,interstitialAdId,videoAdId){
        if(this._bInited){
            return;
        }
        this._BannerAdId = bannerAdId;
        this._IntersisterAdId = interstitialAdId;
        this._VideoAdId = videoAdId;
        this._bInited = true;
    },

    isInited(){
        return this._bInited;
    },

    getBannerAdId() {
        return dyAds._BannerAdId;
    },

    getIntersistAdId(){
        return dyAds._IntersisterAdId;
    },

    getVideoAdId(){
        return dyAds._VideoAdId;
    }
};

export default dyAds;

